package com.example.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sys.component.ControllerBeanPostProcessor;
import com.example.sys.dao.SystemBackendInterfaceMapper;
import com.example.sys.dto.req.MenuContactBackendReq;
import com.example.sys.entity.SystemBackendInterface;
import com.example.sys.service.ISystemBackendInterfaceService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 后端接口信息表 服务实现类
 * </p>
 *
 * @author ywh
 * @since 2024-12-25
 */
@Service
public class SystemBackendInterfaceServiceImpl extends ServiceImpl<SystemBackendInterfaceMapper, SystemBackendInterface> implements ISystemBackendInterfaceService, ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<SystemBackendInterface> backendInterfaces = ControllerBeanPostProcessor.getBackendInterfaceList();
        if (CollectionUtils.isEmpty(backendInterfaces)){
            return;
        }
        //否则加载所有的后端接口出来比对
        List<SystemBackendInterface> nowList = this.list();
        //对比两个集合 没有就新增 不存在的就直接物理删除 不做更新
        Map<String, SystemBackendInterface> systemBackendInterfaceMap = backendInterfaces.stream().collect(Collectors.toMap(SystemBackendInterface::getInterfacePath,e -> e));
        //需要删除的数据
        List<Long> removeIds = Lists.newArrayList();
        for (SystemBackendInterface now : nowList){
            //是否包含 不包含直接删除
            if (!systemBackendInterfaceMap.containsKey(now.getInterfacePath())){
                removeIds.add(now.getId());
                continue;
            }
            //包含那么就从map中删除
            systemBackendInterfaceMap.remove(now.getInterfacePath());
        }
        //不存在的物理删除
        if (CollectionUtils.isNotEmpty(removeIds)){
            this.removeBatchByIds(removeIds);
        }
        //新增的批量新增
        if (CollectionUtils.isNotEmpty(systemBackendInterfaceMap.values())){
            this.saveBatch(systemBackendInterfaceMap.values());
        }
    }

    @Override
    public boolean menuContactBackend(MenuContactBackendReq req) {
        LambdaUpdateWrapper<SystemBackendInterface> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(SystemBackendInterface::getId, req.getBackendInterfaceIdList());
        updateWrapper.set(SystemBackendInterface::getMenuId, req.getMenuId());
        return update(null, updateWrapper);
    }
}
